import { ModalForm, ProFormText } from '@ant-design/pro-form';
import type { FormInstance } from 'antd';
import { message } from 'antd';
import type { UpdateSelfType } from '../typings.d';
import { useRef, useState } from 'react';
import { updateSelfInfo } from '../service';

const UpdateSelfInfo = (props: { user?: USER.CurrentUser }) => {
  const { user } = props;
  const formRef = useRef<FormInstance>();
  const [defaultName, setDefaultName] = useState<string>(user?.userName || '');
  const [defaultPhoneNum, setDefaultPhoneNum] = useState<string>(user?.phoneNumber || '');
  const [defaultEmail, setDefaultEmail] = useState<string>(user?.email || '');
  return (
    <ModalForm<UpdateSelfType>
      title="修改个人信息"
      layout="horizontal"
      width="40vw"
      modalProps={{
        destroyOnClose: true,
      }}
      formRef={formRef}
      labelCol={{ span: 6 }}
      wrapperCol={{ span: 14 }}
      trigger={<a>前往更改个人信息 &gt;</a>}
      onFinish={async (values) => {
        const res = await updateSelfInfo(user?._id || '', values);
        if (res.success) {
          if (values.userName) setDefaultName(values.userName);
          if (values.phoneNumber) setDefaultPhoneNum(values.phoneNumber);
          if (values.email) setDefaultEmail(values.email);
          message.success({ content: res.message, key: 'update_self' });
          // eslint-disable-next-line no-restricted-globals
          location.reload();
          return true;
        }
        message.error({ content: res.message, key: 'update_self' });
        return false;
      }}
    >
      <ProFormText
        required
        label="用户名称"
        placeholder="请输入新用户名"
        name="userName"
        initialValue={defaultName}
        rules={[
          {
            validator: (_, val) => {
              if (!val || val.length < 2)
                return Promise.reject(new Error('用户名称长度不得低于2位'));
              return Promise.resolve(val);
            },
          },
        ]}
      />
      <ProFormText
        name="phoneNumber"
        initialValue={defaultPhoneNum}
        label="手机号码"
        placeholder="请输入手机号"
      />
      <ProFormText
        name="email"
        initialValue={defaultEmail}
        label="电子邮箱"
        placeholder="请输入邮箱"
      />
    </ModalForm>
  );
};
export default UpdateSelfInfo;
